<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="user_id" label="">
        <uni-easyinput placeholder="关联用户ID" v-model="formData.user_id" :disabled="$hasRole('admin')"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_name" label="企业名称" required label-width="200rpx">
        <uni-easyinput v-model="formData.company_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="business_license" label="营业执照" required label-width="200rpx">
        <uni-file-picker file-mediatype="image" return-type="object" limit="1"
          v-model="formData.business_license"></uni-file-picker>
      </uni-forms-item>
      <!-- 新增的法人身份证（国徽面） -->
      <uni-forms-item name="legal_person_idcard_national" label="法人身份证（国徽面）" required label-width="200rpx">
        <uni-file-picker file-mediatype="image" return-type="object" limit="1"
          v-model="formData.legal_person_idcard_national"></uni-file-picker>
      </uni-forms-item>
      <!-- 新增的法人身份证（头像面） -->
      <uni-forms-item name="legal_person_idcard_portrait" label="法人身份证（头像面）" required label-width="200rpx">
        <uni-file-picker file-mediatype="image" return-type="object" limit="1"
          v-model="formData.legal_person_idcard_portrait"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="auth_status" label="认证状态">
        <uni-data-checkbox v-model="formData.auth_status"
          :localdata="formOptions.auth_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="submit_time" label="提交时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.submit_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="audit_time" label="审核时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.audit_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="audit_remark" label="审核备注">
        <uni-easyinput v-model="formData.audit_remark" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="contact_info" label="联系方式">
        <uni-easyinput v-model="formData.contact_info"></uni-easyinput>
      </uni-forms-item>
      <!-- <uni-forms-item name="extra_files" label="补充材料">
        <uni-data-checkbox :multiple="true" v-model="formData.extra_files"></uni-data-checkbox>
      </uni-forms-item> -->
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from '../../js_sdk/validator/merchant-auth.js';
import { PENDING, APPROVED, REJECTED } from '../../utils/constants.js'

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'merchant-auth';
const merchantAuthApi = uniCloud.importObject('merchant-auth-api');

function getValidator(fields) {
  let result = {}
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key]
    }
  }
  return result
}

export default {
  data() {
    let formData = {
      "user_id": "",
      "company_name": "",
      "business_license": null,
      "legal_person_idcard_national": null,
      "legal_person_idcard_portrait": null,
      "auth_status": "",
      "submit_time": null,
      "audit_time": null,
      "audit_remark": "",
      "contact_info": null,
      "extra_files": []
    }
    return {
      formData,
      formOptions: {
        "auth_status_localdata": [
          {
            "value": "pending",
            "text": "审核中"
          },
          {
            "value": "approved",
            "text": "通过"
          },
          {
            "value": "rejected",
            "text": "未通过"
          }
        ]
      },
      rules: {
        ...getValidator(Object.keys(formData))
      },
      active: 0
    }
  },
  onLoad(e) {
    console.log('onload ', e)
    if (e.id) {
      const id = e.id
      this.formDataId = id
      this.getDetail(id)
    }

    this.initStatus()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    /**
     * 一些针对状态的初始化
     */
    initStatus() {
      if (this.formData.auth_status === PENDING) {
        this.active = 1
      } else if (this.formData.auth_status === APPROVED) {
        this.active = 2
      } else if (this.formData.auth_status === REJECTED) {
        this.active = 3
      }
    },

    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true
      })
      this.$refs.form.validate().then((res) => {
        return this.submitForm(res)
      }).catch(() => {
      }).finally(() => {
        uni.hideLoading()
      })
    },

    /**
     * 提交表单
     */
    submitForm(value) {
      return merchantAuthApi.updateByManager(this.formDataId, value).then(res => {
        if (code === 0) {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          // setTimeout(() => uni.navigateBack(), 500)
        }
        else if (code === 500) {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }
      })
    },

    /**
     * 获取表单数据
     * @param {Object} id
     */
    getDetail(id) {
      uni.showLoading({
        mask: true
      })
      db.collection(dbCollectionName).doc(id).field("user_id,company_name,business_license,legal_person_idcard_national,legal_person_idcard_portrait,auth_status,submit_time,audit_time,audit_remark,contact_info,extra_files").get().then((res) => {
        const data = res.result.data[0]
        if (data) {
          this.formData = data
          this.formData.auth_status = data?.auth_status || PENDING
          console.log('getDetail', data)
        }
      }).catch((err) => {
        uni.showModal({
          content: err.message || '请求服务失败',
          showCancel: false
        })
      }).finally(() => {
        uni.hideLoading()
      })
    }
  }
}
</script>
